﻿using Microsoft.ServiceModel.WebSockets;
using Microsoft.Web.WebSockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace ezCloud.Api.Controllers
{
    [RoutePrefix("api/ExternalOutput")]
    public class ExternalOutputController : ApiController
    {
        [Route("WS")]
        public HttpResponseMessage Get(string username)
        {
            if (username != "test")
            {
                HttpContext.Current.AcceptWebSocketRequest(new ChatWebSocketHandler(username));
                return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
            } else
            {
                return Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }
        class ChatWebSocketHandler : WebSocketHandler
       {
           private static WebSocketCollection _chatClients = new WebSocketCollection();
           public string _username;
    
           public ChatWebSocketHandler(string username)
           {
               _username = username;
           }
    
           public override void OnOpen()
           {
               _chatClients.Add(this);
           }
    
           public override void OnMessage(string message)
           {
                var otherClients = _chatClients.Where(c => ((ChatWebSocketHandler)c)._username != _username).ToList();
                foreach(var client in otherClients)
                {
                    client.Send(_username + ":" + message);
                }
           }
       }
    }
}
